<?php

namespace frontend\controllers;

use bc\controller\WxOAuthController;
use bc\util\Util;
use bc\model\shop\ShopUserModel;
use yii\web\Session;
use bc\model\UserModel;
use bc\model\wc\DoctorModel;

class RegdoctorController extends WxOAuthController
{
	
	public function init()
	{
		parent::init();
		$session = new Session();
		$user = $session->get('user');
		
		if(!$user)
			$this->redirect('/');
	}
	
	/**
	 * 
	 * @return string
	 */
	public function actionIndex()
	{
		return $this->render ( 'index' );
	}
	
	/**
	 * 保存
	 */
	public function actionSave()
	{
		$msg = [];
		$session = new Session ();
		$user = $session->get ( 'user' );
		$openid = $user ['openid'];
		$ShopUserModel = new ShopUserModel ();
		$shopUser = $ShopUserModel->getRow ( [ 
				'wxid' => $openid 
		] );
		
		$mobile = $this->post ( 'mobile' );
		$real_name = $this->post ( 'real_name' );

		if ($shopUser)
		{
			$UserModel = new UserModel ();
			$user = $UserModel->getRow ( [
				'wxid' => $openid
			] );
			if (! $user)
			{
//				// 往bc_user插入数据
//				$user_id = $UserModel->add ( [
//						'ecs_user_id' => $shopUser ['user_id'],
//						'wxid' => $openid,
//						'mobile' => $mobile,
//						'real_name' => $real_name
//				] );
				if(empty($openid))
					$this->redirect('/booking/index');
				$user_id = $UserModel->saveDate($openid,$mobile,$real_name);
			}
			else
			{
				$data['mobile']=$mobile;
				$data['real_name']=$real_name;
				$data['update_time']=date('Y-m-d H:i:s', time());
				$UserModel->modify($data,$user['id']);
				$user_id = $user ['id'];
			}

			// 插入医生表
			$doctorModel = new DoctorModel ();
			$doctor = $doctorModel->getRow ( [ 
					'user_id' => $user_id 
			] );
			if (! $doctor) {

				$did = $doctorModel->add([
					'user_id' => $user_id,
					'phone' => $mobile,
					'hospital_id' => 0,
					'update_time' => time(),
					'create_time' => time(),
					'is_invalid' => 1
				]);

				// 根据openid获取用户的
				$userM = new ShopUserModel ();
				$row = $userM->getRow ( [
					'wxid' => $openid
				] );
				// 生成二维码
				//$url = 'http://test.wx.zhishimama.com/shop/mobile/api.php';
				$url = $this->getEnv();
				$params ['act'] = 'create_ysrwm';
				$params ['ac'] = 'ac';
				$params ['id'] = $row ['user_id'];
				$params ['did'] = $did;
				file_put_contents('url.txt',$url);
				$rs = Util::httpPost ( $url, $params );
			}else{

				$doctorModel->modify(
					['phone'=>$mobile,'update_time'=>time()],
					$doctor['id']
				);
			}
		}
		
		$msg['error'] = 1;
		echo json_encode($msg);
		exit;
	}

	/*
 * 判断是测试服务器还是正式服务器
 * */
	public function getEnv()
	{
		$serverIpList = ['139.196.243.146'];
		$severIpAddress = $_SERVER['SERVER_ADDR'];
		if(in_array($severIpAddress, $serverIpList))
		{
			//正式环境
			return 'http://wx.zhishimama.com/shop/mobile/api.php';
		}else{
			//测试环境
			return 'http://test.wx.zhishimama.com/shop/mobile/api.php';
		}
	}
}

